<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="项目主体">
        <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
          <template #statusSlot="{ model, field }">
            <n-input v-model:value="model[field]" />
          </template>
        </BasicForm>
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef"
        @update:checked-row-keys="onCheckedRow" :bordered="false" :actionColumn="actionColumn">
        <template #tableTitle>
          <n-space>
            <n-button type="primary" :on-click="handleEdit.bind(null, {}, true)">
              <template #icon>
                <n-icon>
                  <PlusOutlined />
                </n-icon>
              </template>
              添加项目主体
            </n-button>
          </n-space>
        </template>
        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editTitle" style="border-radius: 8px;">
      <n-form :model="fromValues" :rules="rules" ref="formRef" label-placement="top" :label-width="120" class="py-4">
        <n-form-item label="主体名称" path="mainName">
          <n-input maxlength="150" show-count placeholder="主体名称" v-model:value="fromValues.mainName" />
        </n-form-item>
        <n-form-item label="主体编码" path="mainCode">
          <n-input maxlength="21" show-count placeholder="请输入配置CODE" v-model:value="fromValues.mainCode" />
        </n-form-item>
      </n-form>
      <div style="justify-content: end;display: flex;">
        <n-space>
          <n-button ghost icon-placement="left" @click="handleCloseModel">
            取消
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </div>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive ,h,unref} from 'vue';
import { useMessage, useDialog, type FormRules } from 'naive-ui';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { ResultEnum } from '@/enums/httpEnum';
import { columns } from './columns';
import { PlusOutlined, DeleteOutlined, EditOutlined } from '@vicons/antd';
import { BasicTable, TableAction } from '@/components/Table';
import { page,save,update,remove } from '@/api/working/working';
const actionRef = ref();
const showModal = ref<boolean>(false);
const formBtnLoading = ref<boolean>(false);
const editTitle = ref<string>('');
const formRef: any = ref(null);
const isAdd = ref<boolean>(true);
const dialog = useDialog();
const message = useMessage();
const defaultValueRef = () => ({
  id: null,
  mainName: '',
  mainCode: '',
});
let fromValues = reactive(defaultValueRef());
const rules: FormRules = {
  mainName: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入主体名称',
  },
  mainCode: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入主体编码',
  },
};
/**
 * 表格查询参数定义
 */
 const schemas: FormSchema[] = [
  {
    field: 'mainName',
    component: 'NInput',
    label: '主体名称',
    componentProps: {
      placeholder: '请输入主体名称',
    },
  },
  {
    field: 'mainCode',
    component: 'NInput',
    label: '主体编码',
    componentProps: {
      placeholder: '请输入主体编码',
    },
  },
];
const [register, { getFieldsValue }] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 80,
  schemas,
});
const loadDataTable = async (res: any) => {
  return await page({ ...getFieldsValue(), ...res });
};
/**
 * 定义操作栏
 */
const actionColumn = reactive({
  width: 250,
  title: '操作',
  key: 'action',
  fixed: 'cen',
  render(record) {
    return h(TableAction as any, {
      style: 'text',
      actions: createActions(record),
    });
  },
});
/**
 * 创建操作栏工具
 * @param record 
 */
function createActions(record) {
  return [
    {
      label: '删除',
      type: 'error',
      color: 'red',
      icon: DeleteOutlined,
      onClick: handleDelete.bind(null, record),
      ifShow: () => {
        return true;
      },
      auth: ['working-project-main-del'],
    },
    {
      label: '编辑',
      type: 'primary',
      icon: EditOutlined,
      onClick: handleEdit.bind(null, record, false),
      ifShow: () => {
        return true;
      },
      auth: ['working-project-main-upd'],
    },
  ];
}

const handleDelete = (record) => {
  dialog.warning({
    title: '警告',
    content: `确定删除${record.mainName}吗？`,
    positiveText: '确定',
    negativeText: '取消',
    style: "border-radius: 8px;",
    onPositiveClick: async () => {
      const data = await remove({ id: record.id });
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = (data.data !== null || data.data !== '') ? data.data : '';
        message.error(data.msg + '-' + resultMsg);
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.msg);
        showModal.value = false;
        reloadTable();
      }
    },
  })
}
const handleEdit = (record,addStatus:boolean) => {
   showModal.value = true;
   isAdd.value = addStatus;
  if (addStatus) {
    editTitle.value = `添加项目主体`;
  } else {
    editTitle.value = `编辑 ${record.mainName}`;
    fromValues = Object.assign(fromValues, record);
  }
}

function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}
/**
 * 查询
 */
 function handleSubmit() {
  reloadTable();
}
/**
 * 重置查询
 */
function handleReset() {
  reloadTable();
}
/**
 * 关闭model,重置数据
 */
const handleCloseModel = () => {
  showModal.value = false;
  resetFrom();
}

/**
 * 确认表单
 */
const confirmForm = (e:any) => {
  e.preventDefault();
    formRef.value.validate(async (errors) => {
        if (!errors) {
            formBtnLoading.value = true;
            const data = isAdd.value ? await save(fromValues) : await update(fromValues);
            if (data.code !== ResultEnum.SUCCESS) {
                const resultMsg = data.data ? data.data : '';
                message.error(data.msg + '-' + resultMsg);
                formBtnLoading.value = false;
            }
            if (data.code === ResultEnum.SUCCESS) {
                message.success(data.msg);
                showModal.value = false;
                formBtnLoading.value = false;
                resetFrom();
                reloadTable();
            }
        } else {
            message.error('请填写完整信息');
        }
    });
}

const resetFrom = () =>{
  fromValues = Object.assign(unref(fromValues), defaultValueRef());
}
</script>

<style lang="less" scoped></style>
